package com.spyz.zk.project1.zkcase;

import org.apache.zookeeper.*;
import org.junit.Test;

import java.io.IOException;

public class DistributeServer {


    private int sessionTimeout=2000;
    private String connectString="master:2181,slave:2181,slave2:2181";;
    private ZooKeeper zk;

    public static void main(String[] args) throws IOException, InterruptedException, KeeperException {
        //  1 获取ZK连接
        DistributeServer server = new DistributeServer();
        server.getConnects();

        //  2 注册服务器
        server.regist(args[0]);

        // 3 启动业务
        server.business();
    }

    private void business() throws InterruptedException {
    Thread.sleep(Long.MAX_VALUE);
    }

    private void regist(String hostname) throws InterruptedException, KeeperException {
        String create = zk.create("/servers/"+hostname, hostname.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);
        System.out.println(hostname+" is online "+create);
    }


    private void getConnects() throws IOException {
        zk = new ZooKeeper(connectString, sessionTimeout, new Watcher() {
            @Override
            public void process(WatchedEvent watchedEvent) {

            }
        });
    }
}
